package com.topisv.tms.utils;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import com.topisv.tms.entity.EdiOrder;
import com.topisv.tms.entity.EdiOrderItem;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

public class JsonUtil {
	
	public static List<EdiOrder> getEdiOrders(String jsonString){
		JSONArray jArray=JSONArray.fromObject(jsonString);
		int length=jArray.size();
		List<EdiOrder> es=new ArrayList<EdiOrder>();
		for(int i=0;i<length;i++){
			JSONObject j=JSONObject.fromObject(jsonString);
			EdiOrder e=getEdiOrder(j);
			es.add(e);
		}
		return es;
	}
	
	public static List<EdiOrder> getEdiOrdersPY(String jsonString) throws Exception{
		JSONObject json = JSONObject.fromObject(jsonString);
		JSONArray jArray=json.getJSONArray("orderList");
		int length=jArray.size();
		List<EdiOrder> es=new ArrayList<EdiOrder>();
		for(int i=0;i<length;i++){
			JSONObject j=jArray.getJSONObject(i);
			EdiOrder e=getEdiOrderPY(j);
			es.add(e);
		}
		return es;
	}
	
	private static EdiOrder getEdiOrder(JSONObject j){
		EdiOrder e = new EdiOrder();

		try {
			if(j.containsKey("skuQty")){
				e.setSkuQty(j.getInt("skuQty"));
			}
			e.setPriori(j.getLong("priori"));
			e.setPosfee(j.getDouble("posfee"));
			if(j.containsKey("actuallyPaid")){
				e.setActuallyPaid(Double.parseDouble(j.getString("actuallyPaid")));// 总金额
			}else if(j.containsKey("ActuallyPaid")){
				e.setActuallyPaid(Double.parseDouble(j.getString("ActuallyPaid")));// 总金额
			}
			
		} catch (Exception e2) {
			
		}
		//店铺
		if(j.containsKey("shopna")){
			e.setShopna(j.getString("shopna"));
		}
		if(j.containsKey("shopId")){
			e.setShopId(j.getString("shopId"));
		}
		if(j.containsKey("shopCode")){
			e.setShopCode(j.getString("shopCode"));
		}
		//作业仓库
		if(j.containsKey("warehouseCode")){
			e.setWarehouseCode(j.getString("warehouseCode"));
			e.setAreaGroupCode(j.getString("warehouseCode"));
		}
		if(j.containsKey("customerCode")){
			e.setCustomerCode(j.getString("customerCode"));
		}
		if(j.containsKey("ordeno")){
			e.setOrdeno(j.getString("ordeno"));
		}
		
		if(j.containsKey("orderType")){
			e.setOrderType(j.getString("orderType"));
		}
		if(j.containsKey("waybillNo")){
			e.setWaybillNo(j.getString("waybillNo"));
		}
		
		e.setWhcode(j.getString("whcode"));
		e.setAddres(j.getString("addres"));// 地址
		e.setAdtime(new Date());
		e.setAduser(j.getString("aduser"));
		e.setBumemo(j.getString("bumemo"));
		e.setBunick(j.getString("bunick"));// 买家昵称
		e.setCacode(j.getString("cacode"));
		e.setOldCacode(j.getString("cacode"));
		e.setCaname(j.getString("caname"));
		e.setCityco(j.getString("cityco"));// 市编码
		e.setCityna(j.getString("cityna"));
		e.setCrtime(new Date());
		e.setCustna(j.getString("custna"));
		e.setDistco(j.getString("distco"));
		e.setDistna(j.getString("distna"));
		e.setFromno(j.getString("fromno"));
		e.setFromty(j.getString("fromty"));
		e.setGymemo(j.getString("gymemo"));
		e.setMobile(j.getString("mobile"));
		e.setOpform(j.getString("opform"));
		e.setOrdeno(j.getString("ordeno"));
		e.setPatime(new Date());
		e.setProvco(j.getString("provco"));// 省编码
		e.setProvna(j.getString("provna"));
		e.setRecena(j.getString("recena"));// 收件人名称
		e.setSememo(j.getString("sememo"));
		e.setShmemo(j.getString("shmemo"));
		e.setShopna(j.getString("shopna"));
		e.setTeleph(j.getString("teleph"));
		JSONArray skuList = j.getJSONArray("skulst");
		List<EdiOrderItem> ediOrdenoItems = new ArrayList<EdiOrderItem>();
		for (Iterator sku = skuList.iterator(); sku.hasNext();) {
			EdiOrderItem ei = new EdiOrderItem();
			JSONObject k = (JSONObject) sku.next();
			if(k.containsKey("oid")){
				ei.setOid(k.getString("oid"));
			}
			if(k.containsKey("oidStatus")){
				ei.setOidStatus(k.getString("oidStatus"));
			}
			if(k.containsKey("ordeno")){
				ei.setOrdeno(k.getString("ordeno"));
			}
			if(k.containsKey("customerCode")){
				ei.setCustomerCode(k.getString("customerCode"));
			}
			if(k.containsKey("waybillNo")){
				ei.setWaybillNo(k.getString("waybillNo"));
			}
			ei.setSku(k.getString("sku"));
			ei.setQty(k.getInt("qty"));
			ei.setPri(k.getDouble("pri"));
			ei.setAmo(k.getDouble("amo"));
			ei.setPro(k.getDouble("pro"));
			ei.setPay(k.getDouble("pay"));
			ei.setDis(k.getDouble("dis"));
			ei.setNam(k.getString("nam"));
			ediOrdenoItems.add(ei);
		}

		e.setSkulst(ediOrdenoItems);
		return e;
	}
	
	private static EdiOrder getEdiOrderPY(JSONObject j) throws Exception{
		EdiOrder e = new EdiOrder();
		if(j.containsKey("orderCode")){
			e.setFromno(j.getString("orderCode"));
			e.setCustomerOrdeno(j.getString("orderCode"));
		}
		if(j.containsKey("createTime")){
			e.setAdtime(TimeUtil.getDateMMSS(j.getString("createTime")));
			e.setPatime(TimeUtil.getDateMMSS(j.getString("createTime")));
		}
		if(j.containsKey("orderStatus")){
			e.setOrderStatus(j.getString("orderStatus"));
		}
		//作业仓库
		e.setWarehouseCode(j.getString("warehouseCode"));
		e.setAreaGroupCode(j.getString("warehouseCode"));
		e.setRecena(j.getString("consigneeUser"));
		e.setCustna(j.getString("consigneeUser"));
		e.setBunick(j.getString("consigneeUser"));
		if(j.containsKey("consigneeZip")){
			e.setPostco(j.getString("consigneeZip"));
		}
		
		if(j.containsKey("consigneePhone")){
			e.setTeleph(j.getString("consigneePhone"));
		}
		if(j.containsKey("consigneeMobile")){
			e.setMobile(j.getString("consigneeMobile"));
		}
		e.setProvna(j.getString("consigneeProvince"));
		e.setProvco(j.getString("consigneeProvinceCo"));
		e.setCityna(j.getString("consigneeCity"));
		e.setDistna(j.getString("consigneeDistrict"));
		e.setAddres(e.getProvna() + e.getCityna()+ e.getDistna() + j.getString("consigneeAddress"));
		e.setSememo(j.getString("sellerMemo"));
		e.setBumemo(j.getString("buyerMemo"));
		e.setStatus("pending");
		e.setCacode(j.getString("logisticCode"));
		e.setOldCacode(j.getString("logisticCode"));
		e.setCaname("");
		e.setActuallyPaid(Double.parseDouble(j.getString("payment")));
		
		e.setIsInvoice("1".equals(j.getString("hasInvoice")));
		
		e.setIsTopay("1".equals(j.getString("payType")));
		e.setCrtime(new Date());
		e.setOrderStatus("ok");
		
		List<EdiOrderItem> item = new ArrayList<EdiOrderItem>();
		JSONArray jsonArray = j.getJSONArray("goodsInfo");
		int sku_num=0;
		for(int i=0; i<jsonArray.size(); i++)
		{
			JSONObject jsonObject = (JSONObject)jsonArray.opt(i);
			EdiOrderItem ediOrderItem = new EdiOrderItem();
			ediOrderItem.setOrdeno(j.getString("orderCode"));
			ediOrderItem.setSku(jsonObject.getString("barcode").trim());
			ediOrderItem.setNam(jsonObject.getString("goodsName"));
			ediOrderItem.setQty(jsonObject.getInt("goodsNum"));
			ediOrderItem.setCrtime(new Date());
			ediOrderItem.setPri(Double.parseDouble(jsonObject.getString("salePrice")));
			ediOrderItem.setPay(0.0);
			ediOrderItem.setCustomerCode(e.getCustomerCode());
			ediOrderItem.setAmo(0.0);
			ediOrderItem.setPro(0.0);
			ediOrderItem.setDis(0.0);
			item.add(ediOrderItem);
			sku_num += ediOrderItem.getQty();
			
		}
		if(sku_num > 1)
		{
			e.setOrderType("multiple");
		}
		else if(sku_num == 1)
		{
			e.setOrderType("single");
		}
		e.setSkuQty(sku_num);
		e.setSkulst(item);
		
		
		return e;
	}
	
	public static EdiOrder getEdiOrder(String jsonString) {
		JSONObject j = JSONObject.fromObject(jsonString);
        return getEdiOrder(j);
	
	}
	public static EdiOrder getEdiOrderPY(String jsonString) throws Exception {
		JSONObject j = JSONObject.fromObject(jsonString);
        return getEdiOrderPY(j);
	
	}


	/**
	 * 从一个JSON数组得到一个java对象集合
	 * 
	 * @param object
	 * @param clazz
	 * @return
	 */
	public static List getDTOList(String jsonString, Class clazz) {
		String key = getKeys(jsonString);
		if (key == null || key.equals("error_response")) {
			return null;
		}
		String className = clazz.getSimpleName().toLowerCase();
		while (!key.equals(className)) {
			if (key.equals("total_results")) {
				return null;
			}
			jsonString = getValue(jsonString, key);
			key = getKeys(jsonString);
		}
		return getList(getValue(jsonString, key), clazz);

	}

	/**
	 * 获得json串的key
	 * 
	 * @param jsonString
	 * @return
	 */
	private static String getKeys(String jsonString) {
		int index = jsonString.indexOf("\"");
		char[] jsonStrings = jsonString.toCharArray();
		StringBuffer sb = new StringBuffer();
		for (int i = index + 1; i < jsonStrings.length; i++) {
			if (jsonStrings[i] == '"') {
				return sb.toString();
			} else {
				sb.append(jsonStrings[i]);
			}
		}
		return null;
	}

	/**
	 * 通过java对象获得json串
	 * @param object
	 * @return
	 */
	public static String getObjectString(Object object) {
		return JSONObject.fromObject(object).toString();
	}

	public static List getList(String jsonString, Class clazz) {
		List list = new ArrayList();
		JSONArray array = JSONArray.fromObject(jsonString);
		for (Iterator iter = array.iterator(); iter.hasNext();) {
			JSONObject jsonObject = (JSONObject) iter.next();
			list.add(JSONObject.toBean(jsonObject, clazz));
		}
		return list;
	}
	
	public static List getList(Object jsonString, Class clazz) {
		List list = new ArrayList();
		JSONArray array = JSONArray.fromObject(jsonString);
		for (Iterator iter = array.iterator(); iter.hasNext();) {
			JSONObject jsonObject = (JSONObject) iter.next();
			list.add(JSONObject.toBean(jsonObject, clazz));
		}
		return list;
	}
	
	public static List getList(String jsonString, Class clazz,Map<String,Class> classs) {
		List list = new ArrayList();
		JSONArray array = JSONArray.fromObject(jsonString);
		
		for (Iterator iter = array.iterator(); iter.hasNext();) {
			JSONObject jsonObject = (JSONObject) iter.next();
			list.add(JSONObject.toBean(jsonObject, clazz,classs));
		}
		return list;
	}
	
	public static List getList(Object jsonString, Class clazz,Map<String,Class> classs) {
		List list = new ArrayList();
		JSONArray array = JSONArray.fromObject(jsonString);
		for (Iterator iter = array.iterator(); iter.hasNext();) {
			JSONObject jsonObject = (JSONObject) iter.next();
			list.add(JSONObject.toBean(jsonObject, clazz,classs));
		}
		return list;
	}

	private static String getValue(String jsonString, String key) {
		return JSONObject.fromObject(jsonString).get(key).toString();
	}
	
	public static void main(String args[]){

	}

}
